package livesun.justiceeternal.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.wangjie.androidbucket.utils.imageprocess.ABShape;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionButton;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionHelper;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionLayout;
import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RFACLabelItem;
import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RapidFloatingActionContentLabelList;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import com.zzhoujay.markdown.MarkDown;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.callback.OnImageClickListener;

import java.util.ArrayList;
import java.util.List;

import livesun.justiceeternal.R;
import livesun.justiceeternal.adapter.Comments;
import livesun.justiceeternal.adapter.ItemsBean;
import livesun.justiceeternal.adapter.ScoreBean;
import livesun.justiceeternal.adapter.ScoreInforAdapter;
import livesun.justiceeternal.base.Contract;
import livesun.justiceeternal.db.love.LoveBean;
import livesun.justiceeternal.db.love.LoveModule;
import livesun.justiceeternal.db.love.SimpleLoveListener;
import livesun.justiceeternal.utils.ConstantUtil;
import livesun.justiceeternal.utils.PreferenceUtil;
import livesun.justiceeternal.utils.ToastUtil;
import livesun.justiceeternal.view.BadgeView;
import livesun.justiceeternal.view.titlebar.DefultTitleBar;
import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by 29028 on 2017/8/10.
 */

public class ScoreInforActivity extends AppCompatActivity implements View.OnClickListener,ScoreInforAdapter.OnItemClickListener,
        RapidFloatingActionContentLabelList.OnRapidFloatingActionContentLabelListListener {

    private TextView title;
    private LinearLayout labelRoot;
    private ItemsBean itemsBean;
    private String headBody;
    private String comentUrl;
    private ScoreInforAdapter mAdapter;
    private RecyclerView mRecyclerView;

    private View footView;
    private List<ScoreBean.LabelsBean> labels;
    private int comments=0;
    private String mUserAvatar;
    private String mUserName;
    private String scoreTitle;
    private LinearLayout linearLayout;
    private String mUserUrl;
    private Intent mIntent;
    private HeaderAndFooterWrapper mWrapper;
    private TextView commentSrc;
    private TextView commentEdit;
    private TextView commentCount;
    List<Comments> mComments=new ArrayList<>();
    SimpleLoveListener simpleLoveListener = new SimpleLoveListener(){
        @Override
        public void onInsertSuccess(LoveBean loveBean) {
            super.onInsertSuccess(loveBean);
            LoveModule.getInstance().queryDocList();
            ToastUtil.showShort("收藏成功~");
        }

        @Override
        public void onInsertError(String message) {
            super.onInsertError(message);
            ToastUtil.showShort("收藏失败 "+message);
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LoveModule.getInstance().registerListener(simpleLoveListener);
             new DefultTitleBar.Builder(this)
                        .setStatusColor(getResources().getColor(R.color.colorAccent))
                        .setTitle("谱页")
                        .setLeftIcon(R.drawable.ic_arrow_back_white)
                        .setDark(false)
                        .creat();
        mIntent = new Intent();
        RichText.initCacheDir(getCacheDir());
        itemsBean = (ItemsBean) getIntent().getSerializableExtra(Contract.ITEMBEAN);
        if(itemsBean!=null){
            labels = itemsBean.getLabels();
            //markdown的谱子
            headBody = itemsBean.getBody();
            //评论条数
            comments = itemsBean.getComments();
            //评论链接
            comentUrl=itemsBean.getComments_url();
            //用户头像
            ScoreBean.UserBean user = itemsBean.getUser();
            if(user!=null){
                //上传谱子的用户头像
                mUserAvatar = user.getAvatar_url();
                //上传谱子用户姓名
                mUserName = user.getLogin();
                //上传谱子用户的github地址
                mUserUrl = user.getHtml_url();
            }
            //标题
            scoreTitle = itemsBean.getTitle();
            Comments comments=new Comments();
            comments.setBody(headBody);
            comments.setUser(itemsBean.getUser());
            mComments.add(comments);

        }

        setContentView(R.layout.activity_recycler);

        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));


        //标题
//        titleHeard = LayoutInflater.from(this).inflate(R.layout.heard_rwo, mRecyclerView, false);
//        title = (TextView) titleHeard. findViewById(R.id.title);
//        setText(title,scoreTitle);
//        labelRoot = (LinearLayout) titleHeard. findViewById(R.id.largeLabel_root);
//        addBadgeView(labelRoot);


        //底部评论
        footView = LayoutInflater.from(this).inflate(R.layout.foot_view, mRecyclerView, false);
        commentCount = (TextView) footView.findViewById(R.id.comment_counts);
        commentEdit = (TextView) footView.findViewById(R.id.comment);
        Button gitButton= (Button) footView.findViewById(R.id.git_button);
        commentSrc = (TextView) footView.findViewById(R.id.comment_src);
        gitButton.setOnClickListener(this);
        commentCount.setText(comments+"条评论");
        if(comments==0){
            commentSrc.setText("来做留言第一人吧");
        }else{
            commentSrc.setText("快来发表你的留言~");
        }

        initRFAB();
        //获取数据
        getDatas();
    }
    private RapidFloatingActionLayout rfaLayout;
    private RapidFloatingActionButton rfaButton;
    private RapidFloatingActionHelper rfabHelper;
    private void initRFAB() {
        rfaLayout= (RapidFloatingActionLayout) findViewById(R.id.rfab_group_sample_fragment_a_rfal);
        rfaButton= (RapidFloatingActionButton) findViewById(R.id.rfab_group_sample_rfab_a);
        RapidFloatingActionContentLabelList rfaContent = new RapidFloatingActionContentLabelList(this);
        rfaContent.setOnRapidFloatingActionContentLabelListListener(this);
        List<RFACLabelItem> items = new ArrayList<>();
        items.add(new RFACLabelItem<Integer>()
                .setLabel("保存本地")
                .setResId(R.mipmap.down_load_icon)
                .setIconNormalColor(Color.parseColor("#fb7299"))
                .setIconPressedColor(Color.parseColor("#263238"))
                .setLabelColor(Color.parseColor("#232323"))
                .setLabelTextBold(false)
                .setLabelBackgroundDrawable(ABShape.generateCornerShapeDrawable(Color.parseColor("#E9EAEA"),5))
                .setWrapper(0)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel("点击收藏")
                .setResId(R.mipmap.love_icon)
                .setIconNormalColor(Color.parseColor("#fb7299"))
                 .setIconPressedColor(Color.parseColor("#263238"))
                .setLabelColor(Color.parseColor("#232323"))
                .setLabelSizeSp(14)
                .setLabelTextBold(false)
                .setLabelBackgroundDrawable(ABShape.generateCornerShapeDrawable(Color.parseColor("#E9EAEA"),5))
                .setWrapper(1)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel("更改样式")
                .setResId(R.mipmap.yangshi)
                .setIconNormalColor(Color.parseColor("#fb7299"))
                .setIconPressedColor(Color.parseColor("#263238"))
                .setLabelColor(Color.parseColor("#232323"))
                .setLabelTextBold(false)
                .setLabelBackgroundDrawable(ABShape.generateCornerShapeDrawable(Color.parseColor("#E9EAEA"),5))
                .setWrapper(2)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel("校对谱子")
                .setResId(R.mipmap.edit_score)
                .setIconNormalColor(Color.parseColor("#fb7299"))
                .setIconPressedColor(Color.parseColor("#263238"))
                .setLabelTextBold(false)
                .setLabelColor(Color.parseColor("#232323"))
                .setLabelBackgroundDrawable(ABShape.generateCornerShapeDrawable(Color.parseColor("#E9EAEA"),5))
                .setWrapper(3)
        );
        rfaContent
                .setItems(items)
                .setIconShadowRadius(5)
                .setIconShadowColor(0xff888888)
                .setIconShadowDy(5)
        ;

        rfabHelper = new RapidFloatingActionHelper(
                this,
                rfaLayout,
                rfaButton,
                rfaContent
        ).build();
    }


    private void addBadgeView(LinearLayout root) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10,0,0,0);
        root.removeAllViews();
        if(labels!=null&&labels.size()>0){
            for(int i=0;i<labels.size();i++){
                BadgeView badgeView=new BadgeView(this);
                badgeView.setText(labels.get(i).getName());
                badgeView.setBadgeBackgroundColor(Color.parseColor("#"+labels.get(i).getColor()));
                badgeView.setLayoutParams(layoutParams);
                badgeView.setTextSize(13);
                badgeView.setTextColor(Color.parseColor("#6C5656"));
                root.addView(badgeView);
            }
        }
    }


    public void getDatas() {
        mAdapter = new ScoreInforAdapter(ScoreInforActivity.this,mComments);
        mAdapter.setOnItemClickListener(ScoreInforActivity.this);
        mWrapper = new HeaderAndFooterWrapper(mAdapter);
//        mWrapper.addHeaderView(titleHeard);
        mWrapper.addFootView(footView);
        mRecyclerView.setAdapter(mWrapper);
        String url=comentUrl;
        if(url!=null){

//            OkGo.get(url)
//                    .tag(this)
//                    .execute(new NoDataCallback<List<Comments>>(this,"加载中") {
//
//
//                        @Override
//                        public void onSuccess(List<Comments> commentses, Call call, Response response) {
//                            mComments.addAll(commentses);
//
//                        }
//
//                        @Override
//                        public void onError(Call call, Response response, Exception e) {
//                            super.onError(call, response, e);
//                            ToastUtil.showShort("评论拉去失败");
//                        }
//
//                        @Override
//                        public void onAfter(@Nullable List<Comments> comments, @Nullable Exception e) {
//                            super.onAfter(comments, e);

//                        }
//                    });
        }

    }

    public void setText(TextView view,String text){
        if(TextUtils.isEmpty(text)){
            view.setText("");
        }else {
            view.setText(text);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.git_button:
                if(commentEdit.getText().toString().trim()!=null){
                    //上传网络，
                    //刷新本地
                    int i = comments + 1;
                    commentCount.setText(i+"条评论");
                    if(comments==0){
                        commentSrc.setText("快来发表你的留言~");
                        comments=i;
                    }
                    Comments comments=new Comments();
                    comments.setBody(commentEdit.getText().toString().trim());
                    ScoreBean.UserBean userBean=new ScoreBean().new UserBean();
                    userBean.setLogin("livesun");
                    comments.setUser(userBean);
                    mAdapter.add(comments);

                    commentEdit.setText("");
                }
                break;
        }
    }

    @Override
    public void onItmeClick(String result) {
        if(!TextUtils.isEmpty(result)){
            mIntent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(result);
            mIntent.setData(content_url);
            startActivity(mIntent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RichText.clear(this);
        LoveModule.getInstance().unRegisterListener(simpleLoveListener);
    }

    @Override
    public void onRFACItemLabelClick(int position, RFACLabelItem rfacLabelItem) {
        change(position,rfacLabelItem);
    }

    @Override
    public void onRFACItemIconClick(int position, RFACLabelItem rfacLabelItem) {
        change(position,rfacLabelItem);
    }

    void change(int position, RFACLabelItem rfacLabelItem) {
        if (position == 2) {
            if (mAdapter != null) {
                boolean isNight = PreferenceUtil.getBoolean(ConstantUtil.SWITCH_MODE_KEY, false);
                if (isNight) {
                    PreferenceUtil.putBoolean(ConstantUtil.SWITCH_MODE_KEY, false);
                } else {
                    PreferenceUtil.putBoolean(ConstantUtil.SWITCH_MODE_KEY, true);
                }
                Snackbar.make(rfaButton, "样式切换成功,请重新进入页面", Snackbar.LENGTH_LONG)
                        .setAction("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                            }
                        }).show();

            }
        }else if(position == 1){
            if(itemsBean!=null){
                LoveBean loveBean = new LoveBean();
                loveBean.setBody(itemsBean.getBody());
                loveBean.setName(itemsBean.getTitle());
                loveBean.setSaveTime(System.currentTimeMillis());
                loveBean.setItemId(itemsBean.getId());
                LoveModule.getInstance().saveLove(loveBean);
            }else {
                ToastUtil.showShort("收藏失败");
            }

        }else if(position == 3){



        }else {
            ToastUtil.showShort("紧急开发中");
        }
        rfabHelper.toggleContent();
    }


}
